
package cn.itcast.service;

import cn.itcast.domain.Permission;
import cn.itcast.domain.Role;
import cn.itcast.domain.User;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 查询后台用户数据
 */

@Component
public class SpringSecurityUserService implements UserDetailsService {


    //远程调用方法
    @Reference
    private UserService userService;

    /**
     * 根据用户名查询用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户(数据库中)
        User user = userService.findUserByUsername(username);
        //判断用户是否存在
        if (user == null) {
            return null;
        }
        Set<Role> roles = user.getRoles();

        //授权
        List<GrantedAuthority> list = new ArrayList<>();

        for (Role role : roles) {
            //添加角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //根据角色获取其所具有的权限
            Set<Permission> permissions = role.getPermissions();
            //遍历
            for (Permission permission : permissions) {
                //给角色授予权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        //将用户的信息(用户名,密码,角色和权限信息) 重新组装为springSecurityUser
        org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return userDetails;
    }
}
